package com.wt.struggle.goodbye.main.fragment

import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.StaggeredGridLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.google.gson.reflect.TypeToken
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.*
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.info.ProUserInfo
import com.wt.struggle.goodbye.main.activity.InvitationDetailsActivity
import com.wt.struggle.goodbye.main.adapter.TuiShopAdapter
import com.wt.struggle.goodbye.user.activity.LoginActivity
import com.xin.lv.yang.utils.adapter.AdapterCallBack
import kotlinx.android.synthetic.main.main_fragment_2.*

class MainFragment2 : ProV4Fragment() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {

        when (what) {

            Send.HOT_TIE_CODE -> {

                removeLoadDialog()
                refreshView.isRefreshing = false

                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult

                    if (result != null && result != "" && result != "null") {
                        val arr: ArrayList<NewsInfo> =
                            gson!!.fromJson(result, object : TypeToken<ArrayList<NewsInfo>>() {}.type)

                        showAdapter(arr)

                    } else {
                        if (isVisibleCode) {
                            showToastShort(activity!!, "无更多数据")
                        }
                    }
                } else {

                    if (isVisibleCode) {
                        showToastShort(activity!!, "无更多数据")
                    }

                }
            }

            Send.SEARCH_LIST -> {

                removeLoadDialog()
                refreshView.isRefreshing = false
                if (netInfo.code == Config.SUCCESS) {
                    val result = netInfo.dataResult

                    if (result != null && result != "" && result != "null") {
                        val arr: ArrayList<NewsInfo> =
                            gson!!.fromJson(result, object : TypeToken<ArrayList<NewsInfo>>() {}.type)

                        showAdapter(arr)

                    } else {
                        if (isVisibleCode) {
                            showToastShort(activity!!, "无更多数据")
                        }
                    }
                }
            }

            Send.COLLECT_CODE -> {
                if (netInfo.code == Config.SUCCESS) {
                    showToastShort(activity!!, "操作成功")

                    isLoad = false
                    page = 1

                    get()

                }

            }
        }

    }


    /**
     * 改变
     */
    private fun change() {

        val info = moreList[clickPosition]

        if (info.isCollection == 1) {
            info.isCollection = 0
            if (info.collectionCount != 0) {
                info.collectionCount--
            }

        } else {
            info.isCollection = 1
            info.collectionCount++
        }

        tuiAdapter.updateByTask(moreList, object : AdapterCallBack<NewsInfo>(list, moreList) {

            override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                return oldList[oldItemPosition].id == newList[newItemPosition].id
            }

            override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                return false
            }

            override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
                Log.i("result", "执行到刷新到此-----")

                val bundle = Bundle()
                val oInfo = oldList[oldItemPosition]
                val nInfo = newList[newItemPosition]

                if (oInfo.isCollection != nInfo.isCollection) {
                    bundle.putInt("isCollection", nInfo.isCollection!!)
                    bundle.putInt("collNum", nInfo.collectionCount)
                }
                return bundle
            }

        })

    }


    /**
     * 构建数据并显示
     */
    private fun showAdapter(arr: ArrayList<NewsInfo>) {
        if (arr.size != 0) {

            moreList.addAll(arr)
            page++

            if (tuiRecyclerView != null) {
                if (isLoad) {
                    addMore(arr)
                } else {
                    tuiAdapter.updateDataClear(arr)
                }
            }
        } else {
            if (isVisibleCode) {
                showToastShort(activity!!, "无更多数据")
            }
        }

    }

    private fun addMore(arr: ArrayList<NewsInfo>) {
        tuiAdapter.updateIn(arr)

    }

    var clickPosition = 0

    lateinit var tuiAdapter: TuiShopAdapter

    val list = arrayListOf<NewsInfo>()
    val moreList = arrayListOf<NewsInfo>()


    /**
     * 是否可见
     */
    var isVisibleCode = false

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        Log.i("result", "qqqq------")

        isVisibleCode = isVisibleToUser

    }

    /**
     * 热帖推荐
     */
    private fun initTuiAdapter() {

        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

        layoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
        tuiRecyclerView.layoutManager = layoutManager

        tuiRecyclerView.setHasTransientState(true)
        tuiAdapter = TuiShopAdapter(activity!!, list)
        tuiAdapter.setHasStableIds(true)

        tuiRecyclerView.adapter = tuiAdapter

        tuiAdapter.itemClickListener = object : ItemClickListener {

            override fun onItemClick(position: Int) {

                val intent = Intent(activity!!, InvitationDetailsActivity::class.java)
                val info = list[position]
                intent.putExtra("info", info)
                startActivity(intent)

            }

            override fun onLongClick(position: Int) {

            }
        }

        tuiAdapter.onCollect = object : TuiShopAdapter.OnCollectListener {

            override fun onCollect(position: Int) {
                if (Share.getToken(activity!!) != null) {

                    this@MainFragment2.clickPosition = position

                    val info = list[position]

                    send!!.collect(info.id.toString(), 1, handler)

                } else {
                    startActivity(Intent(activity!!, LoginActivity::class.java))
                }

            }
        }


    }

    override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.main_fragment_2, container, false)
    }

    var page = 1

    var isLoad = false

    /**
     * 1 为查看所有的热帖   2 为查看指定用户发布的帖子
     */
    var code = 1

    var userInfo: ProUserInfo? = null
    var scanW = 0

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        scanW = ((getW(activity!!) - activity!!.resources.getDimension(R.dimen.dp_30))).toInt()

        initTuiAdapter()

        refreshView.setOnRefreshListener {
            moreList.clear()
            isVisibleCode = true

            list.clear()

            if (tuiAdapter != null) {
                tuiAdapter.notifyDataSetChanged()
                tuiAdapter.cache!!.evictAll()
            }

            Glide.with(activity!!).pauseRequests()

            isLoad = false
            page = 1

            get()

            if (isVisibleCode) {
                showLoadDialog(activity!!, "获取中")
            }

        }

        refreshView.onLoadMore(tuiRecyclerView) {
            isLoad = true

            get()

            if (isVisibleCode) {
                showLoadDialog(activity!!, "获取中")
            }

        }

        isLoad = false
        page = 1

        get()

        if (isVisibleCode) {
            showLoadDialog(activity!!, "获取中")
        }

    }


    /**
     * 获取数据
     */
    fun get() {

        if (code == 1) {

            /// 获取热帖
            send!!.getHotTeiList(page, 50, 0, 1, handler!!)

        } else {

            if (userInfo != null) {
                send!!.getSearchList(page, 50, 0, 0, userInfo!!.appUserId!!.toInt(), "", null, handler!!)
            }
        }

    }
}